package com.yzy.soft.config.aop;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Configuration//定义一个切面
public class LogRecordAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);

    // 定义切点Pointcut
    @Pointcut("execution(* com.yzy.soft.system.controller..*.*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        Object[] args = pjp.getArgs();
        String params = "";
        //获取请求参数集合并进行遍历拼接
        if (args.length > 0) {
            if ("POST".equals(method)) {
                Object object = args[0];
                params=JSONObject.toJSONString(object);
// JSONObject json = JSONObject.fromObject(object);
//               params = json.toString();
                ;
            } else if ("GET".equals(method)) {
                params = queryString;
            }
        }


        logger.info("请求开始===地址:" + url);
        logger.info("请求开始===类型:" + method);
        logger.info("请求开始===参数:" + params);

        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
        // logger.info("请求结束===返回值:" + JSONObject.fromObject(result));
         logger.info("请求结束===返回值:" + JSONObject.toJSONString(result));
        return result;
    }
}